<template>
    <div class="boxs">
        <el-card>
            <el-form :model="queryParams" ref="queryForm" :inline="true">

                <el-form-item label="type">
                    <el-select v-model="queryParams.type" @change="handleQuery">
                        <el-option v-for="item in stateList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="code">
                    <el-select v-model="queryParams.code" @change="handleQuery">
                        <el-option v-for="item in codeList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="EnvType">
                    <el-select v-model="queryParams.pk" @change="handleQuery">
                        <el-option v-for="item in environmentList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker v-model="value1" value-format="yyyy-MM-dd" type="daterange" range-separator="-"
                        :start-placeholder="$t('table.start')" :end-placeholder="$t('table.end')" @change="timeChange">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" size="small"
                        @click="handleQuery">{{ $t('table.search') }}</el-button>
                    <el-button icon="el-icon-refresh" size="small"
                        @click="resetQuery">{{ $t('table.reset') }}</el-button>
                </el-form-item>
            </el-form>
            <div class="flex_between">
                <div></div>
                <el-button size="mini" type="danger"
                    @click="handleBatchDelete()">{{ $t('table.BatchDeletion') }}</el-button>

            </div>
            <el-table border :data="moreArr" style="margin-top: 15px" v-loading="loading">
                <el-table-column label="type" align="center" prop="type" width="120" />

                <el-table-column label="error" align="center" prop="error">
                    <template slot-scope="scope">
                        <div style="cursor: pointer;color: blue;" @click="copyOrder1(scope.row.message)">
                            {{ scope.row.message }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="code" align="center" width="100" prop="code">
                </el-table-column>
                <el-table-column label="version" align="center" width="100" prop="version">
                </el-table-column>

                <el-table-column label="url/text" align="center" prop="url" width="200">
                    <template slot-scope="scope">
                        <div v-if="scope.row.url">
                            <img :src="scope.row.url" alt="Image"
                                style="max-width: 100px; max-height: 100px; cursor: pointer;"
                                @click="openDialog(scope.row.url)" />
                        </div>
                        <div v-else style="cursor: pointer; color: blue;  " @click="copyOrder2(scope.row.product)">
                            {{ scope.row.product }}
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="update_date" align="center" width="180" prop="update_date">
                </el-table-column>
                <el-table-column :label="$t('feedback.operate')" align="center" width="120">
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger"
                            @click="handleDelete(scope.$index, scope.row)">{{ $t('table.delete') }}</el-button>

                    </template>

                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total"  :page.sync="queryParams.page" :limit.sync="queryParams.size"
                @pagination="getMore" />
        </el-card>

        <el-dialog :visible.sync="dialogVisible" @close="dialogVisible = false">
            <img :src="currentImageUrl" alt="Large Image" style="width: 100%;" />
        </el-dialog>
    </div>
</template>
<script>
import { getImageError, deleteHandel, batchDeleteHandel } from "@/api/beauty";

import pk from "@/utils/pk";
export default {
    name: "RequestRecord",
    data() {
        return {
            environmentList: [
                {
                    id: 'com.seamobitech.BeautyAI',
                    name: 'Production'
                },
                {
                    id: 'com.tcdemotc.testApp',
                    name: 'Testing'
                },
            ],
            codeList: [
                {
                    name: '0',
                    id: '0'
                },
                {
                    name: '1',
                    id: '1'
                },
                {
                    name: '2',
                    id: '2'
                },
                {
                    name: '3',
                    id: '3'
                },
                {
                    name: '4',
                    id: '4'
                },
                {
                    name: '5',
                    id: '5'
                },
                {
                    name: '6',
                    id: '6'
                },
                {
                    name: '7',
                    id: '7'
                },
                {
                    name: '8',
                    id: '8'
                },
            ],
            currentImageUrl: '',
            queryParams: {
                page: 1,
                size: 10,
                dateRange: {
                    start: "",
                    end: "",
                },
                type: "",
                code:'',
                pk: 'com.seamobitech.BeautyAI'
            },
            stateList: [
                {
                    id: 'face',
                    name:'face'
                },
                {
                    id: 'makeup',
                    name: 'makeup'
                },
                {
                    id: 'product',
                    name: 'product'
                },
                {
                    id: 'imageToProduct',
                    name: 'imageToProduct'
                },
            ],
            productIdList: [
                {
                    name: 'subs.week',
                    id: 'subs.week'
                },
                {
                    name: 'subs.week.premium',
                    id: 'subs.week.premium'
                },
                {
                    name: 'subs.month',
                    id: 'subs.month'
                },
                {
                    name: 'subs.month.premium',
                    id: 'subs.month.premium'
                },
                {
                    name: 'subs.year',
                    id: 'subs.year'
                },
                {
                    name: 'subs.year.premium',
                    id: 'subs.year.premium'
                },
                {
                    name: 'pro.lifetime',
                    id: 'pro.lifetime'
                },
                {
                    name: 'NA',
                    id: 'NA'
                },
            ],
            total: 0,
            loading: false,
            addLoading: false,
            moreArr: [],
            dialogVisible: false,
            form: {
                description: "",
                file: "",
            },
            search: "",
            rules: {
                token: [
                    { required: true, message: "Please enter token", trigger: "blur" },
                ],
                productId: [{ required: true, message: "Please enter productId", trigger: "change" }],
            },
            value1: "",
        };
    },
    watch: {
        'form.state'(newVal) {
            if (newVal === '2') {
                this.form.productId = 'NA'; // Set to NA ID
            }
        }
    },
    created() {
        this.getMore();
        // this.init()
    },
    methods: {


        copyOrder() {
            const input = document.createElement('textarea');
            input.value = this.form.orderId;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);

        },
        copyOrder1(data1) {
            let data = this.extractErrorFromJsonString(data1)
            const input = document.createElement('textarea');
            input.value = data;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        extractErrorFromJsonString(jsonString) {
            if (JSON.parse(jsonString).content && JSON.parse(jsonString).content.includes('```json')) {
                if (JSON.parse(jsonString).content.charAt(0) === '`') {
                    if (JSON.parse(JSON.parse(jsonString).content.replace(/```json|```/g, '').trim()).error) {
                        return JSON.parse(JSON.parse(jsonString).content.replace(/```json|```/g, '').trim()).error
                    } else {
                        return jsonString
                    }
                } else {
                    return JSON.parse(jsonString).content

                }
                
            } else {

                return JSON.parse(jsonString).refusal || JSON.parse(jsonString).content
            }
        },
        copyEmail() {
            const input = document.createElement('textarea');
            input.value = this.form.email;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);

        },
        copyEmail1(data) {
            const input = document.createElement('textarea');
            input.value = data;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) {
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        uploadHandel(e) {
            this.form.file = e.file;
        },
        remeveFile() {
            this.form.file = "";
        },
        timeChange() {
            this.queryParams.dateRange.start = this.value1[0];
            this.queryParams.dateRange.end = this.value1[1];
            this.handleQuery();
        },
        getKeyByValue(object, value) {
            return Object.keys(object).find((key) => object[key] === value);
        },
        async getMore() {
            this.loading = true;
            let { data, total } = await getImageError(this.queryParams);
            this.loading = false;
            this.moreArr = data;
            this.total = total;
        },

        handleQuery() {
            this.queryParams.page = 1;
            this.getMore();
        },
        // async affirm() {
        //     this.$refs["ruleForm"].validate(async (valid) => {
        //         if (!valid) return;
        //         try {
        //             this.addLoading = true;
        //             await restoreUserSubscriptionStatus(this.form);
        //             this.addLoading = false;
        //             this.$message.success("操作成功");
        //             this.getMore();
        //             this.dialogVisible = false;
        //         } catch (e) {
        //             this.addLoading = false;
        //         }
        //     });
        // },
        openDialog(url) {
            this.currentImageUrl = url;
            this.dialogVisible = true;
        },
        handleEdit(i, row) {
            if (row.images) {
                row.imagesList = row.images.split('|')
            }
            if (row.state == '0') {
                row.state = '1'
            }
            this.form = Object.assign({}, row);
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles(); // 清除文件列表
            }
            this.dialogVisible = true;
        },
        copyOrder2(data1) {
            const input = document.createElement('textarea');
            input.value = data1;
            document.body.appendChild(input);
            input.select();
            try {
                document.execCommand('copy');
                this.$message({
                    message: 'Text copied to clipboard!',
                    type: 'success'
                });
            } catch (err) { 
                this.$message({
                    message: 'Failed to copy text.',
                    type: 'error'
                });
            }
            document.body.removeChild(input);
        },
        handleDelete(index, row) {
            this.$confirm(this.$t('review.deleteText1'), this.$t('review.deleteText2'), {
                confirmButtonText: this.$t('review.confirm'),
                cancelButtonText: this.$t('review.close'),
                type: "error",
            }).then(async () => {
                try {
                    this.elloading = this.$loading({
                        lock: true,
                        text: 'Loading',
                        spinner: 'el-icon-loading',
                        background: 'rgba(0, 0, 0, 0.7)'
                    });
                    await deleteHandel({ id: row.id, url: row.url });
                    this.getMore();
                    this.$message({
                        message: "success!",
                        type: "success",
                    });
                } catch (error) {
                    // 在这里可以添加错误处理逻辑
                    console.error("Error during deletion:", error);
                    this.$message({
                        message: "Failed to delete!",
                        type: "error",
                    });
                } finally {
                    this.addLoading = false;
                    this.elloading.close();

                }





                
            });
        },
        handleBatchDelete() {
            this.$confirm(this.$t('review.deleteText1'), this.$t('review.deleteText2'), {
                confirmButtonText: this.$t('review.confirm'),
                cancelButtonText: this.$t('review.close'),
                type: "error",
            }).then(async () => {
                this.elloading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                try {
                    let arr = this.moreArr.map(item => {
                        return {
                            id: item.id,
                            url: item.url || null
                        };
                    });
                    await batchDeleteHandel({ items: arr });
                    this.getMore();
                    this.$message({
                        message: "success!",
                        type: "success",
                    });
                } catch (error) {
                    // 在这里可以添加错误处理逻辑
                    console.error("Error during deletion:", error);
                    this.$message({
                        message: "Failed to delete!",
                        type: "error",
                    });
                } finally {
                    this.addLoading = false;
                    this.elloading.close();

                }

                
            });
        },
        resetQuery() {
            this.queryParams.pk = 'com.seamobitech.BeautyAI';

            this.queryParams.type = null;
            this.queryParams.code = null;
            this.queryParams.package_name = null;
            this.queryParams.dateRange.start = null;
            this.queryParams.dateRange.end = null;
            this.queryParams.page = 1;
            this.value1 = "";
            this.getMore();
        },
    },
};
</script>
<style lang="scss" scoped>
.boxs {
    padding: 20px;
}

::v-deep.el-input.is-disabled .el-input__inner {
    color: #333 !important;
}

::v-deep.el-textarea.is-disabled .el-textarea__inner {
    color: #333 !important;
}

::v-deep .el-upload {
    width: 100% !important;
}

::v-deep .el-upload-dragger {
    width: 100% !important;
}
</style>